package com.ustc.hewei.rpc.client.loadbalance.impl;

import com.ustc.hewei.rpc.client.loadbalance.LoadBalanceChoose;
import com.ustc.hewei.rpc.common.protocol.Service;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;

/**
* @description: 轮询负载均衡
* @author hewei
* @date 2022/8/19 10:21
* @version 1.0
*/

public class RoundRobin implements LoadBalanceChoose {
    private final HashMap<String, Integer> serviceRoundCount;

    public RoundRobin() {
        serviceRoundCount = new HashMap<>();
    }

    @Override
    public Service chooseService(String serviceName, List<Service> services) {
        // 也可以用ConcurrentHashMap来代替
        synchronized (serviceRoundCount) {
            Integer count = serviceRoundCount.getOrDefault(serviceName, 0);
            if (count >= services.size()) count = 0;
            serviceRoundCount.put(serviceName, count + 1);
            return services.get(count);
        }
    }

    @Override
    public Service nextService(List<Service> services, String serviceName, int offset) {
        try {
            String clientIp = InetAddress.getLocalHost().getHostAddress();
            int code = clientIp.hashCode();
            int index = (code & Integer.MAX_VALUE) % services.size() + offset;
            return services.get(index % services.size());
        } catch (UnknownHostException e) {
            throw new RuntimeException("获取下一个服务失败！", e);
        }
    }
}
